package com.jrfid.smartcabinet.demo.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.LogUtils
import com.jrfid.smartcabinet.demo.utils.Config
import com.jrfid.smartcabinet.demo.utils.KTDataUtils
import com.xuhao.didi.core.iocore.interfaces.ISendable
import com.xuhao.didi.core.pojo.OriginalData
import com.xuhao.didi.core.protocol.IReaderProtocol
import com.xuhao.didi.socket.client.sdk.OkSocket
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager
import java.lang.Exception
import java.nio.ByteOrder

class MainViewModel : ViewModel() {
    val TAG = this.javaClass.simpleName

    /**
     * 显示设置按钮
     */
    var showSettingMenu = MutableLiveData(true)

    /**
     * 读取ic卡
     */
    var readICCard = MutableLiveData<String>()

    /**
     * ic卡读取结果
     */
    var currentICCardNo = MutableLiveData<String>()

    private val socketReceiver = object : SocketActionAdapter() {
        override fun onSocketReadResponse(info: ConnectionInfo?, action: String?, data: OriginalData?) {
            super.onSocketReadResponse(info, action, data)
            data?.let {
                LogUtils.dTag(TAG, "收到数据：${KTDataUtils.byteArrayToHex(it.headBytes)} - ${KTDataUtils.byteArrayToHex(it.bodyBytes)}")
            }
        }

        override fun onSocketWriteResponse(info: ConnectionInfo?, action: String?, data: ISendable?) {
            super.onSocketWriteResponse(info, action, data)
            data?.let {
                LogUtils.dTag(TAG, "发送成功：${it.toString()}")
            }
        }

        override fun onSocketConnectionSuccess(info: ConnectionInfo, action: String?) {
            super.onSocketConnectionSuccess(info, action)
            LogUtils.dTag(TAG, "连接成功")
//            val model = SocketMsgModel(CMDData.R2000.realTimeInventory())
        }

        override fun onSocketConnectionFailed(info: ConnectionInfo?, action: String?, e: Exception?) {
            super.onSocketConnectionFailed(info, action, e)
            LogUtils.dTag(TAG, "连接失败")
        }

        override fun onSocketDisconnection(info: ConnectionInfo?, action: String?, e: Exception?) {
            super.onSocketDisconnection(info, action, e)
            e?.printStackTrace()
            LogUtils.dTag(TAG, "断开连接")
        }
    }

    init {

    }

    fun reconnectReader() {
        val readerList = Config.getCabinetList()
        readerList.forEach {
            it.readerIP.get()?.let { ip ->
                it.readerPort.get()?.let { port ->
                    connectReaderDevice(ip, port.toIntOrNull() ?: 4001)
                }
            }
        }
    }

    private fun connectReaderDevice(ip: String, port: Int): IConnectionManager {
        val manager = OkSocket.open(ConnectionInfo(ip, port))
        val builder = OkSocketOptions.Builder(manager.option)
        builder.setReaderProtocol(object : IReaderProtocol {

            override fun getHeaderLength(): Int {
                return 2
            }

            override fun getBodyLength(header: ByteArray, byteOrder: ByteOrder?): Int {
                return KTDataUtils.hexToInt(KTDataUtils.byteToHex(header[1]))
            }
        })
        manager.option(builder.build())
        manager.registerReceiver(socketReceiver)
        manager.connect()
        return manager
    }

}